#include "DBDatabase.h"

namespace SQLDoc
{
	DBDatabase::DBDatabase(void) 
		: DBObject(DBObject::DBOTYPE_DATABASE)
		,m_isValid(false)
		,m_isActive(false)
	{ }

	DBDatabase::~DBDatabase(void)
	{ }

	bool DBDatabase::isActive()
	{
		return m_isActive;
	}

	void DBDatabase::ensureActive(QSqlDatabase &db)
	{
		if (!m_isActive)
		{
			DBConnection* connection = reinterpret_cast<DBConnection*>(m_parentItem);
			connection->setActiveDatabase(this);

			use(db);
		}
	}

	void DBDatabase::deactivate()
	{
		m_isActive = false;
	}

	int DBDatabase::selectTables(bool refresh /*= false*/)
	{
		if (refresh)
		{
			qDeleteAll(m_tables);
			m_isValid = false;
		}

		if (m_tables.count() == 0 && !m_isValid)
		{
			fillTables();
		}

		return m_tables.count();
	}

	int DBDatabase::tablesCount(void)
	{
		int count = -1;

		if (m_isValid)
		{
			count = m_tables.count();
			if (!count)
				count = m_childItems.count();

			return count;
		}

		return selectTables();
	}

	void DBDatabase::rewriteTables(void)
	{
		int count = m_tables.count();

		while (m_tables.count() > 0)
		{
			addChild(m_tables.at(0));
			m_tables.removeAt(0);
		}
	}
}
